import { FairyEditor, FairyGUI, System, UnityEngine } from 'csharp';
import File from '../../com/io/File';
import FileUtils from '../../com/utils/FileUtils';
import ImageUtils from '../../com/utils/ImageUtils';
import LoadUtils from '../../com/utils/LoadUtils';
import LocalCookie from '../../com/utils/LocalCookie';
import Global from '../../Global';
import EGlist from "../common/EGlist";
import EditableTreeItem from "../items/EditableTreeItem";
import UISplitImgItem from '../items/UISplitImgItem';
import PanelRegister from "../PanelRegister";
import UIBaseWindow from "../UIBaseWindow";
import UISystem from '../UISystem';
import UICmdView from './UICmdView';
/*
 *
 *@author clong 2020.11.01
 */
export default class UIPluginView extends UIBaseWindow {

    private btn_confim: FairyGUI.GButton;
    private btn_save: FairyGUI.GButton;
    private btn_dos: FairyGUI.GButton;
    private img_load: FairyGUI.GLoader;
    private txt_info: FairyGUI.GLabel;
    private txt_size: FairyGUI.GTextField;

    private eglist_items: EGlist;
    private eglist_split_imgs: EGlist;

    protected clickItemCallBack: FairyGUI.EventCallback1 = null;

    constructor() {

        super("plugin", "UIPluginView");
    }

    registerClasses(): void {

        super.registerClasses();

        PanelRegister.registerClass("plugin", "UISplitImgItem", UISplitImgItem);
        PanelRegister.registerClass("plugin", "UITestItem", EditableTreeItem);
    }

    initUI(): void {

        super.initUI();

        this.eglist_split_imgs.name = "test";

        this.clickItemCallBack = (context: FairyGUI.EventContext) => {
            this.clickItem(context.data);
        }
        this.eglist_items.AddEventListener(FairyEditor.FEvents.CLICK_ITEM, this.clickItemCallBack);
    }

    show(data: any): void {

        super.show(data);

        FairyGUI.GRoot.inst.onTouchBegin.Add((context: FairyGUI.EventContext) => { this.mouseDown(context); }); //这个的remove也无法移除
        FairyGUI.GRoot.inst.onTouchEnd.Add((context: FairyGUI.EventContext) => { this.mouseUp(context); });

        let url: string = LocalCookie.Inst.read("cacheDir");//本地缓存目录
        if (url) {
            let files = System.IO.Directory.GetFiles(url);
            this.openFiles(files);
        }
    }

    private mouseDown(context: FairyGUI.EventContext): void {

        // console.log( "===========>mouseDown." );
        FairyGUI.Timers.inst.AddUpdate(this.timeCall);
    }

    private timeCall = () => {
        this.moveTarget();
    }

    private moveTarget(): void {

        // if( Global.stage && Global.stage.touchPosition ){
        //     let mx = Global.stage.touchPosition.x;//Laya.MouseManager.instance.mouseX;
        //     let my = Global.stage.touchPosition.y;//Laya.MouseManager.instance.mouseY;
        //     let target: any = FairyGUI.GRoot.inst.touchTarget
        //     // console.log( "----->moveTarget." + target + " mx: " + mx + " my: " + my);
        // }        
    }

    private mouseUp(context: FairyGUI.EventContext): void {

        FairyGUI.Timers.inst.Remove(this.timeCall);//-----------BUG 这里没移除掉

        // FairyGUI.GRoot.inst.onTouchEnd.Clear();//这种移除方式正常,但是应该会移除所有这种监听的事件
        // console.log( "===========>mouseUp." );
    }

    //当前选择目录
    private selectFile: File = null;

    private clickItem(item: any): void {

        if (item instanceof FairyGUI.GButton) {
            this.showInfo("clickItem---------->: " + item.title);

            this.selectFile = new File(item.title);
            if (this.selectFile.isImg) {
                LoadUtils.loadImage(this.selectFile.url, Laya.Handler.create(this, this.loadImg, [this.selectFile.url]));
            }
        }
    }

    private loadImg(url: string, tex: FairyGUI.NTexture): void {

        this.img_load.texture = tex;//显示图片

        let name = File.getFileName(url);
        this.eglist_split_imgs.name = name;

        this.splitImage(tex, 6);//切割图片
    }

    private splitImage(tex: FairyGUI.NTexture, column: number): void {

        let arr: Array<FairyGUI.NTexture> = ImageUtils.splitTexture(tex, column);

        this.eglist_split_imgs.array = arr;
    }

    onBtnClick(btn: any): void {

        super.onBtnClick(btn);

        if (btn == this.btn_confim) {
            // let url = System.IO.Directory.GetCurrentDirectory();
            //打开本地目录
            FileUtils.BrowseForDirectory(Laya.Handler.create(this, (file: string) => {
                LocalCookie.Inst.write("cacheDir", file);//写入本地缓存
                let files = System.IO.Directory.GetFiles(file);
                this.openFiles(files);
            }));
        } else if (btn == this.btn_save) {//保存图片
            if (this.selectFile == null) {
                FairyEditor.App.Alert("请先选择保存文件");
                return;
            }
            let url: string = this.selectFile.url;
            if (this.eglist_split_imgs.array.length > 0) {
                for (let i = 0; i < this.eglist_split_imgs.numChildren; i++) {
                    let item: any = this.eglist_split_imgs.getChildAt(i);
                    if (item instanceof UISplitImgItem) {
                        let tex = item.texture.nativeTexture as UnityEngine.Texture2D;
                        let savePath = url.substr(0, url.lastIndexOf(".")) + "\\" + item.name + ".png";
                        FileUtils.savePic(tex, savePath);
                    }
                }
            }
        } else if (btn == this.btn_dos) {
            UISystem.Inst.CreateWindowView(UICmdView);
        }
    }

    private openFiles(files: any): void {

        // let files = System.IO.Directory.GetFiles( UrlUtils.FAIRUI );
        let arr: Array<string> = [];
        this.showInfo("----->files.length: " + files.Length);
        for (let i = 0; i < files.Length; i++) {
            let str = files.get_Item(i);
            // this.showInfo("----->files: " + str );
            arr.push(str);
        }
        this.eglist_items.array = arr;
        this.eglist_items.selectedIndex = -1;
        this.eglist_items.selectedIndex = 0;
    }

    private showInfo(text: string): void {

        this.txt_info.text += text + "\n";
    }

    onResize(): void {

        this.panel.SetSize(Global.stageWidth, Global.stageHeight);
        super.onResize();

        // this.showInfo("-------->onResize stageWidth: " + Global.stageWidth + " stageHeight: "+Global.stageHeight);
        // this.showInfo("-------->onResize scaleX: " + Global.stage.scaleX + " scaleY: "+Global.stage.scaleY);

        this.txt_size.text = "尺寸: " + Global.stageWidth + "X" + Global.stageHeight;

        // console.log("-------->view.x: " + this.x + " view.y: " + this.y);
        // console.log("-------->txt_info.x: " + this.txt_info.x + " txt_info.y: " + this.txt_info.y);
    }
}